﻿using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;

namespace RandomDemo.TokenFiles
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class TokenFilter : Attribute, IAsyncActionFilter
    {
        /// <summary>
        /// Token过滤器，返回值在User_Id或者Error
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //判断header中是否存在Authorization字段，与前端协商好的
            var str = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (str != null)
            {
                var temp = Token.Validata(str);
                //字符串转为对象
                //TokenResult = JsonConvert.DeserializeObject<JwtPayload>(temp);
                if (context.Controller.GetType().GetProperty("TokenResult") != null)
                {
                    if (temp.Length > 100 && temp != "token过期" && temp != "token验证错误")
                    {
                        (context.Controller as dynamic).TokenResult = JsonConvert.DeserializeObject<JwtPayload>(temp);
                    }
                    else
                    {
                        var TokenResult = new JwtPayload();
                        TokenResult.Add("error", "未知错误");
                        (context.Controller as dynamic).TokenResult = TokenResult;
                    }
                }
                else
                {
                    Console.WriteLine("不包含TokenResult公开属性");
                }

            }
            //获取用户    
            //if (context.HttpContext.User != null)
            //{
            //    //秦哥给的代码，没明白怎么用
            //    var claims = context.HttpContext.User.Claims;
            //    if (claims != null)
            //    {
            //        var claim = claims.Where(e => e.Type == "user_info").FirstOrDefault();
            //        var admin = claims.Where(e => e.Type == "admin").FirstOrDefault();
            //        if (claim != null)
            //        {
            //            foreach (var item in context.ActionArguments)
            //            {
            //                if (context.ActionArguments[item.Key] is LoginController)
            //                {
            //                    ((LoginController)context.ActionArguments[item.Key]).u = JsonConvert.DeserializeObject<Controllers.User>(claim.Value);
            //                }
            //            }
            //        }
            //    }
            await next();
        }
    }
}
